import serial
import threading
import time

class SerialCommunication:
    def __init__(self, port='/dev/ttyUSB0', baudrate=38400, timeout=0.1):
        """
        初始化串口通信类
        :param port: 串口端口号，例如 'COM3' 或 '/dev/ttyUSB0'
        :param baudrate: 波特率，默认为 9600
        :param timeout: 读取超时时间，默认为 1 秒
        """
        self.port = port
        self.baudrate = baudrate
        self.timeout = timeout
        self.serial_port = None
        self.read_thread = None
        self.is_running = False

        self._open_serial()
        self._start_read_thread()

    def _open_serial(self):
        """打开串口"""
        try:
            self.serial_port = serial.Serial(self.port, self.baudrate, timeout=self.timeout)
            print(f"Serial port {self.port} opened successfully.")
        except serial.SerialException as e:
            print(f"Failed to open serial port {self.port}: {e}")

    def _start_read_thread(self):
        """启动读取线程"""
        self.is_running = True
        self.read_thread = threading.Thread(target=self._read_data)
        self.read_thread.daemon = True  # 设置为守护线程
        self.read_thread.start()

    def _read_data(self):
        """串口数据读取方法，作为线程运行"""
        while self.is_running:
            if self.serial_port and self.serial_port.is_open:
                try:
                    data = self.serial_port.readline()#.decode().strip()
                    if data:
                        self._handle_data(data)
                except Exception as e:
                    print(f"Error reading data: {e}")
            time.sleep(0.01)

    def _handle_data(self, data):
        """处理接收到的数据"""
        print(f"Received data: {data}")

    def send_data(self, data):
        """发送数据到串口"""
        if self.serial_port and self.serial_port.is_open:
            try:
                self.serial_port.write(data)
                print(f"Sent data: {data}")
            except Exception as e:
                print(f"Failed to send data: {e}")

    def close(self):
        """关闭串口和停止线程"""
        self.is_running = False
        if self.read_thread and self.read_thread.is_alive():
            self.read_thread.join()
        if self.serial_port and self.serial_port.is_open:
            self.serial_port.close()
            print(f"Serial port {self.port} closed.")

# 使用示例
if __name__ == "__main__":
    serial_com = SerialCommunication(port="COM3", baudrate=9600)
    try:
        # 在这里可以发送数据
        serial_com.send_data("Hello")
        time.sleep(5)  # 等待几秒以接收数据
    finally:
        serial_com.close()  # 结束时关闭串口
